package com.dq.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by EDZ on 2018/3/17.
 */
@Controller
public class HelloRfc {

    private static final Logger LOGGER = LoggerFactory.getLogger(HelloRfc.class);

    private int count = 1;
    /**
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/rfc2617", method = RequestMethod.GET)
    public String index(HttpServletRequest req, HttpServletResponse resp) {
       String auth = req.getHeader("Authorization");
       if(!StringUtils.isEmpty(auth)){
           if(!checkHeaderAuth(req, resp)){
               resp.setStatus(401);
               resp.setHeader("Cache-Control", "no-store");
               resp.setDateHeader("Expires", 0);
               resp.setHeader("WWW-authenticate", "Basic admin=\"admin+"+count+"\"");
               LOGGER.info("",count);
               return "error";
           }
       }else{
           LOGGER.info("this is next step");
           return "success";
       }
       return "index";
    }

    private boolean checkHeaderAuth(HttpServletRequest request, HttpServletResponse response){
        String auth = request.getHeader("Authorization");
        LOGGER.info("auth encoded in base64 is " + getFromBASE64(auth));
        if ((auth != null) && (auth.length() > 6)) {
            auth = auth.substring(6, auth.length());
            String decodedAuth = getFromBASE64(auth);
            LOGGER.info("auth decoded from base64 is " + decodedAuth);
            if(decodedAuth.equals("admin:admin"+count)){
                count++;
                return true;
            }
            return false;
        }else{
            return false;
        }

    }

    private String getFromBASE64(String s) {
        if (s == null) {
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b,"UTF-8");
        } catch (Exception e) {
            return null;
        }
    }
}
